<template>
  <view class="allorders-container">
    <!-- 标签导航 -->
    <view class="tab">
      <!-- 使用 v-for 来循环创建标签 -->
      <text 
        v-for="(tab, index) in tabs" 
        :key="index" 
        :class="{ 'active': currentTab === tab.type }"
        @click="onTabClick(tab.type)">
        {{ tab.name }}
      </text>
    </view>
    <!-- 内容显示区域 -->
    <view class="content">
      <!-- 全部订单 -->
      <view v-if="currentTab === 'all'" class="order-list">
        <view 
          v-for="(order, index) in allOrders" 
          :key="index" 
          class="order-item"
        >
          <view class="order-details">
            <text class="order-product-name">{{ order.productName }}</text>
            <text class="order-product-price">￥{{ order.productPrice * (order.quantity || 1) }}</text>
            <text class="order-product-description">{{ order.description }}</text>
            <!-- 仅当 order.url 存在时展示图片 -->
            <image v-if="order.url" :src="order.url" class="order-product-image" mode="aspectFit"></image>
            <text class="order-status">{{ beautifyStatus(order.status) }}</text>
          </view>
        </view>
      </view>
      <!-- 待付款订单 -->
      <view v-else-if="currentTab === 'unpaid'" class="order-list">
        <view v-for="(order, index) in filterOrdersByStatus('unpaid')" :key="index" class="order-item">
          <view class="order-details">
            <text class="order-product-name">{{ order.productName }}</text>
            <text class="order-product-price">￥{{ order.productPrice * (order.quantity || 1) }}</text>
            <text class="order-product-description">{{ order.description }}</text>
            <!-- 仅当 order.url 存在时展示图片 -->
            <image v-if="order.url" :src="order.url" class="order-product-image" mode="aspectFit"></image>
            <text class="order-status">{{ beautifyStatus(order.status) }}</text>
            <view class="order-actions">
              <button class="cancel-btn" @click="cancelOrder(order.productId, 'unpaid')">取消订单</button>
              <button class="confirm-btn" @click="confirmPayment(order.productId)">确认付款</button>
            </view>
          </view>
        </view>
      </view>
      <!-- 待发货订单 -->
      <view v-else-if="currentTab === 'unshipped'" class="order-list">
        <view v-for="(order, index) in filterOrdersByStatus('unshipped')" :key="index" class="order-item">
          <view class="order-details">
            <!-- 订单详情 -->
            <text class="order-product-name">{{ order.productName }}</text>
            <text class="order-product-price">￥{{ order.productPrice * (order.quantity || 1) }}</text>
            <text class="order-product-description">{{ order.description }}</text>
            <image v-if="order.url" :src="order.url" class="order-product-image" mode="aspectFit"></image>
            <text class="order-status">{{ beautifyStatus(order.status) }}</text>
            <view class="order-actions">
              <button class="urgency-btn" @click="urgeDelivery(order)">催发货</button>
            </view>
          </view>
        </view>
      </view>
      <!-- 待收货订单 -->
      <view v-else-if="currentTab === 'unreceived'" class="order-list">
        <view v-for="(order, index) in filterOrdersByStatus('unreceived')" :key="index" class="order-item">
          <view class="order-details">
            <!-- 订单详情 -->
            <text class="order-product-name">{{ order.productName }}</text>
            <text class="order-product-price">￥{{ order.productPrice * (order.quantity || 1) }}</text>
            <text class="order-product-description">{{ order.description }}</text>
            <image v-if="order.url" :src="order.url" class="order-product-image" mode="aspectFit"></image>
            <text class="order-status">{{ beautifyStatus(order.status) }}</text>
            <view class="order-actions">
              <button class="evaluate-btn" @click="goToEvaluate(order)">去评价</button>
            </view>
          </view>
        </view>
      </view>
      <!-- 待评价订单 -->
      <view v-if="currentTab === 'tobeevaluated'" class="order-list">
        <view v-for="(order, index) in evaluateOrders" :key="index" class="order-item">
          <view class="order-details">
            <!-- 订单详情 -->
            <text class="order-product-name">{{ order.productName }}</text>
            <text class="order-product-price">￥{{ order.productPrice * (order.quantity || 1) }}</text>
            <text class="order-product-description">{{ order.description }}</text>
            <image v-if="order.url" :src="order.url" class="order-product-image" mode="aspectFit"></image>
            <text class="order-status">{{ beautifyStatus(order.status) }}</text>
            <!-- 待评价订单的操作按钮根据实际需求添加 -->
          </view>
        </view>
      </view>
      <!-- 其他状态的订单可以按照类似方式实现，这里省略以节省空间 -->
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      product: {},
      currentTab: 'all',
      tabs: [
        { type: 'all', name: '全部' },
        { type: 'unpaid', name: '待付款' },
        { type: 'unshipped', name: '待发货' },
        { type: 'unreceived', name: '待收货' },
        { type: 'tobeevaluated', name: '待评价' },
      ],
      orders: [], // 初始订单数组为空
      evaluateOrders: [], // 初始待评价订单数组为空
    };
  },
  computed: {
    // 计算属性，合并 orders 和 evaluateOrders 数组
    allOrders() {
      return this.orders.concat(this.evaluateOrders);
    }
  },
  onLoad(options) {
    this.loadProductData();
    this.loadOrders();
    this.loadEvaluateOrders();
    this.loadBuyProducts(); // 新增方法加载buyProducts数据
    if (options && options.isPaid) {
      this.updateOrderStatus(options.isPaid === 'true');
    }
  },
  onShow() {
    this.refreshCurrentTab();
  },
  methods: {
    onTabClick(type) {
      this.currentTab = type;
      uni.setStorageSync('currentTab', type);
    },
    beautifyStatus(status) {
      const statusMap = {
        'unpaid': '订单待付款',
        'unshipped': '订单待发货',
        'unreceived': '订单已签收',
        'tobeevaluated': '订单已评价',
        'cancelled': '已取消',
      };
      return statusMap[status] || '未知状态';
    },
    loadProductData() {
      const product = uni.getStorageSync('product') || {};
      this.product = product.id ? product : {};
    },
    loadOrders() {
      let ordersData = uni.getStorageSync('orders') || [];
      this.orders = ordersData
        .map(order => ({
          ...order,
          description: order.description || '暂无描述',
          url: order.url || '',
          quantity: order.quantity || 1, // 默认数量为1
          isPaid: order.isPaid || false // 增加一个标记字段，初始值为 false
        }))
        .filter(order => order.productName && order.productPrice); // 过滤掉没有商品数据的订单
    },
    loadEvaluateOrders() {
      let evaluateOrdersData = uni.getStorageSync('evaluateOrders') || [];
      this.evaluateOrders = evaluateOrdersData;
    },
    loadBuyProducts() {
      let buyProducts = uni.getStorageSync('buyProducts') || [];
      this.orders = this.orders.concat(
        buyProducts
          .filter(product => product.name && product.price) // 过滤掉没有商品数据的产品
          .map(product => ({
            productId: product.id,
            productName: product.name,
            productPrice: product.price,
            status: product.isPaid ? 'unshipped' : 'unpaid',
            description: product.description || '暂无描述',
            url: product.url || '',
            quantity: product.quantity || 1, // 默认数量为1
            isPaid: product.isPaid || false // 增加一个标记字段，初始值为 false
          }))
      );
      uni.setStorageSync('orders', this.orders);
    },
    filterOrdersByStatus(status) {
      return this.orders.filter(order => order.status === status);
    },
    updateOrderStatus(isPaid) {
      const status = isPaid ? 'unshipped' : 'unpaid';
      const newOrder = {
        productId: this.product.id,
        productName: this.product.name,
        productPrice: this.product.price,
        status,
        description: this.product.description || '暂无描述',
        url: this.product.url || '',
        quantity: this.product.quantity || 1, // 默认数量为1
        isPaid: isPaid // 根据付款状态更新标记字段
      };
      // 确保只有有效的订单数据才会被添加
      if (newOrder.productId && newOrder.productName && newOrder.productPrice) {
        this.orders.push(newOrder);
        uni.setStorageSync('orders', this.orders);
      }
    },
    cancelOrder(productId, status) {
      const index = this.orders.findIndex(order => order.productId === productId && order.status === status);
      if (index !== -1) {
        this.orders.splice(index, 1);
        uni.setStorageSync('orders', this.orders);
      }
    },
    confirmPayment(productId) {
      const index = this.orders.findIndex(order => order.productId === productId && order.status === 'unpaid');
      if (index !== -1) {
        this.orders[index].status = 'unshipped';
        this.orders[index].isPaid = true; // 更新标记字段
        const order = this.orders.splice(index, 1)[0]; // 从待付款订单中移除
        this.orders.push(order); // 将订单添加到待发货订单列表
        uni.setStorageSync('orders', this.orders);
        uni.showToast({
          title: '付款成功，订单已转到待发货',
          icon: 'none',
          duration: 2000,
        });
      } else {
        uni.showToast({
          title: '订单已确认付款',
          icon: 'none',
          duration: 2000,
        });
      }
    },
    urgeDelivery(order) {
      const index = this.orders.findIndex(o => o.productId === order.productId && o.status === 'unshipped');
      if (index !== -1) {
        this.orders[index].status = 'unreceived';
        this.orders[index].description = '商品已发货，请注意查收。';
        uni.setStorageSync('orders', this.orders);
        uni.showToast({
          title: '已经为您发货',
          icon: 'none',
          duration: 2000,
        });
      }
    },
    goToEvaluate(order) {
      const index = this.orders.findIndex(o => o.productId === order.productId && o.status === 'unreceived');
      if (index !== -1) {
        // 从 orders 数组中移除并添加到 evaluateOrders 数组
        const orderToEvaluate = this.orders.splice(index, 1)[0];
        orderToEvaluate.status = 'tobeevaluated'; // 更新状态为待评价
        this.evaluateOrders.push(orderToEvaluate); // 添加到待评价订单数组
        uni.setStorageSync('orders', this.orders);
        uni.setStorageSync('evaluateOrders', this.evaluateOrders);
        uni.showToast({
          title: '已转至待评价',
          icon: 'none',
          duration: 2000,
        });
      }
    },
    refreshCurrentTab() {
      const storedTabType = uni.getStorageSync('currentTab') || 'all';
      this.currentTab = storedTabType;
    },
  },
};
</script>

<style>
.allorders-container {
  padding: 10px;
  background-color: #f2f4f5; /* 背景颜色 */
}
.tab {
  display: flex;
  justify-content: space-around;
  margin-bottom: 10px;
}

.tab text {
  cursor: pointer;
  padding: 5px;
  border-bottom: 2px solid transparent;
  font-size: 16px;
}

.tab .active {
  border-bottom: 2px solid blue;
  color: blue;
}
.order-details{
  position: relative;
  border-radius: 30rpx;
  background-color: white;
  height: 400rpx;
  margin: 0 15rpx 0 15rpx;
  margin-top: 30rpx;
}
.order-product-name{
  position: absolute;
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  top: 20rpx;
  padding-left: 300rpx;
}
.order-product-price{
  position: absolute;
  font-size: 30rpx;
  color: #e64340;
  top: 200rpx;
  padding-left: 300rpx;
}
.order-product-image{
  position: absolute;
  width: 100%;
  border-radius: 10rpx;
  width: 250rpx;
  height: 250rpx;
  top: 20rpx;
  left: 10rpx;
}
.order-product-description{
  position: absolute;
  font-size: 20rpx;
  color: #666;
  top: 100rpx;
  padding-left: 300rpx;
}
.order-status{
  position: absolute;
  color: black;
  font-weight: bold;
  top: 300rpx;
  left: 20rpx;
}
.order-actions {
  position: absolute;
  bottom: 10rpx;
  right: 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.cancel-btn, .confirm-btn {
  margin: 0 10rpx;
  padding: 10rpx;
  border: 1px solid #ccc;
  border-radius: 10rpx;
  color: white;
  background-color: #fff;
  outline: none;
  background-color: red;
}
.order-actions {
  position: absolute;
  bottom: 10rpx;
  right: 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.urgency-btn {
  margin: 0 10rpx;
  padding: 10rpx;
  border: 1px solid #ccc; /* 根据需要调整颜色 */
  border-radius: 10rpx;
  color: #333; /* 文字颜色 */
  background-color: #fff; /* 背景颜色 */
  outline: none;
  /* 可以添加其他样式以匹配您原有的样式 */
}
</style>

